package com.yungu.swift.assets.driver.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alicp.jetcache.anno.Cached;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.yungu.swift.assets.driver.dao.CarInsuranceMapper;
import com.yungu.swift.assets.driver.dao.CarMapper;
import com.yungu.swift.assets.driver.dao.DriverMapper;
import com.yungu.swift.assets.driver.model.dto.CarDto;
import com.yungu.swift.assets.driver.model.dto.CarInsuranceDto;
import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.model.param.AdminCarPageParam;
import com.yungu.swift.assets.driver.model.vo.CarExportVo;
import com.yungu.swift.assets.driver.service.CarService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.model.admin.AdminPageParam;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.Map;

/**
 * CarServiceImpl
 **/
@Service
public class CarServiceImpl extends BaseServiceImpl<CarDto> implements CarService {

    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarInsuranceMapper carInsuranceMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    protected IMapper<CarDto> getMapper() {
        return carMapper;
    }

    @Override
    public <U extends AdminPageParam> ResponseData<PageVo<CarDto>> queryPage(U u) {
        PageBounds pageBounds = new PageBounds(u.getPageNum(), u.getPageSize());
        PageList<CarDto> pageList = this.getMapper().queryPage(BeanMap.create(u), pageBounds);
        PageVo<CarDto> pageVo = new PageVo(u.getPageNum(), u.getPageSize(), pageList.getPaginator().getTotalCount());
        pageList.stream().forEach(carDto -> {
            List<DriverDto> driverDtoList = driverMapper.list(MapUtils.build("carUuid", carDto.getUuid()));
            carDto.setDriverList(driverDtoList);
        });
        pageVo.setItems(pageList);
        return ResponseData.buildSuccessResponse(pageVo);
    }

    @Override
    public ResponseData<Boolean> add(CarDto carDto) {
        List<CarDto> list = carMapper.list(MapUtils.build("plateNum", carDto.getPlateNum()));
        if (CollectionUtils.isNotEmpty(list)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "车牌号已存在");
        }
        List<CarInsuranceDto> carInsuranceList = carDto.getCarInsuranceList();
        if (CollectionUtils.isNotEmpty(carInsuranceList)) {
            for (CarInsuranceDto carInsuranceDto : carDto.getCarInsuranceList()) {
                carInsuranceDto.setUuid(StringUtils.buildUUID());
                carInsuranceDto.setCarUuid(carDto.getUuid());
                carInsuranceDto.setVehicleNo(carDto.getPlateNum());
                carInsuranceDto.setCreateBy(carDto.getCreateBy());
                carInsuranceDto.setCreateOn(carDto.getCreateOn());
            }
        }
        Boolean execute = transactionTemplate.execute(transactionStatus -> {
            boolean flag = carMapper.add(carDto) > 0;
            if (CollectionUtils.isNotEmpty(carInsuranceList)) {
                //移除旧保险信息
                carInsuranceMapper.delByCarUuid(carDto.getUuid());
                int count = carInsuranceMapper.addBatch(carInsuranceList);
                flag = flag || count> 0;
            }
            return flag;
        });
        return ResponseData.buildSuccessResponse("新增成功", execute);
    }

    @Override
    public ResponseData<Boolean> edit(CarDto carDto) {
        List<CarInsuranceDto> carInsuranceList = carDto.getCarInsuranceList();
        if (CollectionUtils.isNotEmpty(carInsuranceList)) {
            for (CarInsuranceDto carInsuranceDto : carDto.getCarInsuranceList()) {
                carInsuranceDto.setUuid(StringUtils.buildUUID());
                carInsuranceDto.setCarUuid(carDto.getUuid());
                carInsuranceDto.setVehicleNo(carDto.getPlateNum());
                carInsuranceDto.setCreateBy(carDto.getUpdateBy());
                carInsuranceDto.setCreateOn(carDto.getUpdateOn());
            }
        }
        Boolean execute = transactionTemplate.execute(transactionStatus -> {
            boolean flag = carMapper.update(carDto) > 0;
            if (CollectionUtils.isNotEmpty(carInsuranceList)) {
                //移除旧保险信息
                int a = carInsuranceMapper.delByCarUuid(carDto.getUuid());
                int count = carInsuranceMapper.addBatch(carInsuranceList);
                flag = flag ||  count> 0;
            }
            return flag;
        });
        return ResponseData.buildSuccessResponse("更新成功", execute);
    }

    @Override
    public ResponseData<List<CarDto>> listExtend(Map<String, Object> carParamsMap) {
        return ResponseData.buildSuccessResponse(carMapper.listExtend(carParamsMap));
    }

    @Override
    public ResponseData<CarDto> get(Map<String, Object> carParamsMap) {
        List<CarDto> list = carMapper.list(carParamsMap);
        if (CollectionUtils.isNotEmpty(list)) {
            CarDto carDto = list.get(0);
            List<CarInsuranceDto> insuranceList = carInsuranceMapper.list(MapUtils.build("carUuid", carParamsMap.get("uuid")));
            carDto.setCarInsuranceList(insuranceList);
            return ResponseData.buildSuccessResponse(carDto);
        }
        return ResponseData.buildSuccessResponse(null);
    }

    @Cached(name = "jetCache:assets:getCar:",key = "#uuid",expire =150)
    @Override
    public ResponseData<CarDto> get(String uuid) {
        return get(MapUtils.build("uuid", uuid));
    }

    @Override
    public ResponseData<Integer> getCarCount(String appid, String agentUuid, String companyUuid) {
        Map<String, Object> params = MapUtils.build(4);
        params.put("appid", appid);
        params.put("agentUuid", agentUuid);
        params.put("companyUuid", companyUuid);
        return ResponseData.buildSuccessResponse(carMapper.getCarCount(params));
    }

    @Override
    public ResponseData<List<CarExportVo>> listExport(AdminCarPageParam carPageParam) {
        return ResponseData.buildSuccessResponse(carMapper.listExport(MapUtils.convertObjToMap(carPageParam)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData<Boolean> importCar(List<CarDto> carDtoList, List<CarInsuranceDto> carInsuranceDtoList, List<CarDto> updateCarDtoList, List<CarInsuranceDto> updateCarInsuranceDtoList) {
        if (!carDtoList.isEmpty()) {
            carMapper.addBatch(carDtoList);
        }
        if (!carInsuranceDtoList.isEmpty()) {
            carInsuranceMapper.addBatch(carInsuranceDtoList);
        }
        if (!updateCarDtoList.isEmpty()) {
            carMapper.updateBatch(updateCarDtoList);
        }
        if (!updateCarInsuranceDtoList.isEmpty()) {
            carInsuranceMapper.updateBatch(updateCarInsuranceDtoList);
        }
        return ResponseData.buildSuccessResponse("导入成功", Boolean.TRUE);
    }

    @Override
    public ResponseData<List<Map<String, String>>> getDriInfo(Map params) {
        return ResponseData.buildSuccessResponse("查询成功", carMapper.getDriInfo(params));
    }

    @Override
    public ResponseData<List<CarDto>> plateNumSearch(Map<String, Object> map) {
        return ResponseData.buildSuccessResponse(carMapper.plateNumSearch(map));
    }

    @Override
    public int update(CarDto carDto) {
        return carMapper.update(carDto);
    }
}
